﻿using ZyGame.Execute;
using System;
using System.Collections;
using UnityEngine;

namespace ZyGame
{
    public static class ParallelRunnableExtension
    {
        public static Runnable<object> Execute(this ParallelRunnable builder, Runnable handle)
        {
            IEnumerator Runner()
            {
                if (handle == null)
                {
                    yield break;
                }
                yield return handle.Waitting();
            }
            return builder.Execute(Runner);
        }

        public static Runnable<object> Execute<T>(this ParallelRunnable builder, Runnable<T> handle)
        {
            IEnumerator Runner()
            {
                if (handle == null)
                {

                    yield break;
                }
                yield return handle.Waitting();
            }
            return builder.Execute(Runner);
        }

        public static ParallelRunnable DoFinish(this ParallelRunnable builder, Action action)
        {
            IEnumerator Runner()
            {
                if (action != null)
                {
                    try
                    {
                        action();
                    }
                    catch (Exception e)
                    {
                        Client.Console.WriteError(e);
                    }
                }
                yield break;
            }
            return builder.DoFinish(Runner);
        }

        public static ParallelRunnable DoFinish<T>(this ParallelRunnable builder, Action<T> action, T args)
        {
            return builder.DoFinish(() => { action(args); });
        }

        public static ParallelRunnable DoFinish<T, T2>(this ParallelRunnable builder, Action<T, T2> action, T args, T2 args2)
        {
            return builder.DoFinish(() => { action(args, args2); });
        }
        public static ParallelRunnable DoFinish(this ParallelRunnable builder, Runnable handle)
        {
            IEnumerator Runner()
            {
                if (handle == null)
                {

                    yield break;
                }
                yield return handle.Waitting();
            }
            return builder.DoFinish(Runner);
        }
    }
}